<template>
  <view class="container">
    <!-- 录入说明卡片 -->
    <view class="info-card welcome-card">
      <view class="welcome-header" @longpress="handleClearDraft">
        <u-icon name="home" color="#0ea5e9" size="32"></u-icon>
        <text class="welcome-title">录入房产信息</text>
      </view>
      <text class="welcome-desc">请填写以下信息，以便我们更好地展示您的房产。</text>
    </view>

    <!-- 基础信息表单 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="info-circle" color="#0ea5e9" size="18"></u-icon>
        <text class="title-text">房产基础信息</text>
      </view>

      <u--form :model="formData" ref="uForm" :rules="rules" label-width="100">
        <u-form-item label="房产名称" prop="name" required>
          <u-input v-model="formData.name" placeholder="请输入房产名称" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="房产类型" prop="type" required>
          <u-input v-model="formData.type" placeholder="请选择房产类型" border="surround" :disabled="true"></u-input>
          <view slot="right" @click="showTypePicker">
            <u-button>选择</u-button>
          </view>
        </u-form-item>

        <u-form-item label="面积(㎡)" prop="area" required>
          <u-input v-model="formData.area" placeholder="请输入房产面积" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="价格(元)" prop="price" required>
          <u-input v-model="formData.price" placeholder="请输入房产价格" border="surround" :disabled="formData.facePrice"></u-input>
          <view slot="right" @click="formData.facePrice= !formData.facePrice">
            <u-button>面议</u-button>
          </view>
        </u-form-item>

        <u-form-item label="户型" prop="layout">
          <u-input v-model="formData.layout" placeholder="例如：3室2厅 / 双层商铺" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="楼层信息" prop="floorInfo">
          <u-input v-model="formData.floorInfo" placeholder="例如：1-2层 / 高层" border="surround"></u-input>
        </u-form-item>
        <u-form-item label="建造年份" prop="buildYear">
          <u-input v-model="formData.buildYear" placeholder="请选择建造年份" border="surround" :disabled="true"></u-input>
          <view slot="right" @click="showBuildYearPicker">
            <u-button>选择</u-button>
          </view>
        </u-form-item>
      </u--form>
    </view>

    <!-- 地址信息表单 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="map" color="#10b981" size="18"></u-icon>
        <text class="title-text">地址信息</text>
      </view>

      <u-form :model="formData" ref="uForm2" label-width="100">

        <template v-for="(item,index) in phoneNumbers">
          <u-form-item :label="`联系人 ${index+1}` " required>
            <u-input v-model="item.name" placeholder="姓名" border="surround"></u-input>
          </u-form-item>
          <u-form-item label="电话" required>
            <u-input v-model="item.phone" placeholder="联系电话" type="number" border="surround"></u-input>
          </u-form-item>
        </template>

        <u-form-item label="详细地址" prop="address" required>
          <u-input v-model="formData.address" placeholder="请输入详细地址" border="surround"></u-input>
          <view slot="right" @click="handleCheckLocation()">
            <u-button>选择</u-button>
          </view>
        </u-form-item>

      </u-form>
    </view>

    <!-- 房产标签 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="tags" color="#ef4444" size="18"></u-icon>
        <text class="title-text">房产标签</text>
      </view>
      <view class="tags-section">
        <u-tag v-for="tag in availableTags" :key="tag" :text="tag" :type="selectedTags.includes(tag) ? 'primary' : 'info'" :plain="!selectedTags.includes(tag)" shape="circle" @click="toggleTag(tag)"></u-tag>
      </view>
      <view class="custom-tag-input" v-if="showCustomTagInput">
        <u-input v-model="customTag" placeholder="输入自定义标签" border="surround">
          <template slot="suffix">
            <u-button @tap="addCustomTag" text="确定" type="success" size="mini"></u-button>
          </template>
        </u-input>
      </view>
      <u-button type="info" :plain="true" size="mini" @click="toggleCustomTagInput" :custom-style="{ marginTop: '16rpx' }">
        {{ showCustomTagInput ? '取消' : '添加自定义标签' }}
      </u-button>
    </view>

    <!-- 房产描述 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="file-text" color="#8b5cf6" size="18"></u-icon>
        <text class="title-text">房产描述</text>
      </view>
      <u-textarea v-model="formData.description" placeholder="请详细描述房产的特点、优势、周边环境等信息" :maxlength="500" count height="200"></u-textarea>
    </view>

    <!-- 图片上传 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="camera" color="#06b6d4" size="18"></u-icon>
        <text class="title-text">房产图片</text>
      </view>
      <view class="upload-section">
        <text class="upload-desc">请上传房产图片（最多5张）</text>
        <view class="upload-grid">
          <view class="upload-item" v-for="(image, index) in uploadedImages" :key="index">
            <u-image :src="image" width="200rpx" height="200rpx" border-radius="16rpx" mode="aspectFill"></u-image>
            <view class="delete-btn" @click="deleteImage(index)">
              <u-icon name="close" color="#fff" size="12"></u-icon>
            </view>
          </view>
          <view class="upload-placeholder" v-if="uploadedImages.length < 5" @click="chooseImage">
            <u-icon name="plus" color="#94a3b8" size="32"></u-icon>
            <text class="upload-text">添加图片</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-action-bar">
      <u-button type="info" :plain="true" shape="circle" :custom-style="draftBtnStyle" @click="saveDraft">
        保存草稿
      </u-button>
      <u-button type="primary" shape="circle" :custom-style="submitBtnStyle" @click="handleSave" :loading="isSubmitting">
        {{ isSubmitting ? '提交中...' : '提交发布' }}
      </u-button>
    </view>

    <!-- 提示组件 -->
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
  const KEY_DRAFT = "House_draft"
  import AppDefine from '@/utils/define.js'

  export default {
    data() {
      return {
        isSubmitting: false,
        showCustomTagInput: false,
        customTag: '',

        formData: {
          name: '', // 房产名称
          type: '住宅', // 房产类型
          layout: '', // 户型（如：2室1厅1卫）
          phone: '', // 联系电话
          contactPerson: '', // 联系人
          address: '', // 详细地址
          area: 70, // 面积（平方米）
          buildYear: 2000, // 建筑年份
          city: '昆明市', // 城市
          description: '', // 房产描述
          district: '东川区', // 区域
          floorInfo: '', // 楼层
          imageUrls: [], // 图片地址
          isEnabled: true, // 是否启用
          isFeatured: false, // 是否推荐
          position: '', // 坐标位置
          price: 0, // 价格（元）
          facePrice: false, //
          province: '云南省', // 省份
          tagsJson: [] // 标签
        },
        phoneNumbers: [
          { name: '', phone: '' }
        ],
        selectedTags: [],
        uploadedImages: [],

        // 表单验证规则
        rules: {
          name: [
            { required: true, message: '请输入房产名称', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择房产类型', trigger: 'change' }
          ],
          address: [
            { required: true, message: '请选择详细地址', trigger: 'blur' }
          ]
        },

        // 选项数据
        typeOptions: ['商铺', '住宅', '写字楼', '公寓', '别墅', '厂房', '土地', '其他'],
        buildYearOptions: [], // 动态生成 
        availableTags: [
          '商业综合体', '高端商圈', '品牌店', '地铁沿线', '投资优选',
          '学区房', '精装修', '拎包入住', '交通便利', '景观房', '新房', '二手房'
        ],
        draftBtnStyle: {
          flex: '1',
          marginRight: '24rpx',
          height: '88rpx',
          fontSize: '32rpx'
        },
        submitBtnStyle: {
          flex: '1',
          background: 'linear-gradient(135deg, #0ea5e9, #06b6d4)',
          border: 'none',
          height: '88rpx',
          fontSize: '32rpx'
        }
      }
    },
    onLoad() {
      try {
        const draft = uni.getStorageSync(KEY_DRAFT);
        // console.log(draft)
        if (draft) {
          uni.showModal({
            title: '发现草稿',
            content: '是否恢复之前保存的草稿？',
            success: (res) => {
              if (res.confirm) {
                this.formData = { ...draft };
                this.selectedTags = draft.tagsJson ?? []
                this.availableTags = draft.availableTags ?? []

                if (draft.phoneNumbers) {
                  this.phoneNumbers = draft.phoneNumbers;
                }
              }
            }
          });
        }
      } catch (error) {
        console.error('恢复草稿失败:', error);
      }
    },
    methods: {
      handleClearDraft() {
        uni.setStorageSync(KEY_DRAFT, '');
        this.$u.toast('草稿已清空')
      },
      handleCheckLocation() {
        uni.chooseLocation({
          latitude: this.formData.lat || 26.086244,
          longitude: this.formData.lng || 103.182078,
          success: (res) => {
            this.formData.address = res.address
            this.formData.addressName = res.name
            this.formData.lat = res.latitude
            this.formData.lng = res.longitude
            this.formData.position = `[${res.longitude},${res.latitude}]`
            // console.log(res)
          }
        })
      },

      // 显示类型选择器
      showTypePicker() {
        let list = this.typeOptions
        uni.showActionSheet({
          itemList: list,
          success: (res) => {
            this.formData.type = list[res.tapIndex]
          }
        })


      },
      // 显示建造年份选择器
      showBuildYearPicker() {
        const currentYear = new Date().getFullYear();
        let list = []
        for (let i = currentYear; i >= 1900; i--) {
          list.push(String(i));
        }
        uni.showActionSheet({
          itemList: list,
          success: (res) => {
            this.formData.buildYear = list[res.tapIndex]
          }
        })
      },
      // 切换标签选择
      toggleTag(tag) {
        const index = this.selectedTags.indexOf(tag);
        if (index > -1) {
          this.selectedTags.splice(index, 1);
        } else {
          if (this.selectedTags.length < 8) { // 限制标签数量
            this.selectedTags.push(tag);
          } else {
            this.$refs.uToast.show({
              message: '最多只能选择8个标签',
              type: 'warning'
            });
          }
        }
      },

      // 切换自定义标签输入
      toggleCustomTagInput() {
        this.showCustomTagInput = !this.showCustomTagInput;
        if (!this.showCustomTagInput) {
          this.customTag = '';
        }
      },

      handleAddPhone() {
        let item = {
          name: '',
          phone: ''
        }
        if (this.phoneNumbers.length > 2) {
          return
        }
        this.phoneNumbers.push(item)
      },
      // 添加自定义标签
      addCustomTag() {
        if (this.customTag.trim() && !this.selectedTags.includes(this.customTag.trim())) {
          if (this.selectedTags.length < 8) {
            this.selectedTags.push(this.customTag.trim());
            this.availableTags.push(this.customTag.trim());
            this.customTag = '';
            this.showCustomTagInput = false;
          } else {
            this.$refs.uToast.show({
              title: '最多只能选择8个标签',
              type: 'warning'
            });
          }
        }
      },

      // 选择图片
      chooseImage() {
        uni.chooseImage({
          count: 5 - this.uploadedImages.length, // 最多5张
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            this.uploadedImages = this.uploadedImages.concat(res.tempFilePaths);
          }
        })
      },
      // 删除图片
      deleteImage(index) {
        this.uploadedImages.splice(index, 1);
      },

      // 保存草稿
      async saveDraft() {
        try {
          const draftData = {
            ...this.formData,
            tagsJson: this.selectedTags,
            availableTags: this.availableTags,
            phoneNumbers: this.phoneNumbers
          }
          console.log('保存草稿:', draftData);

          // 模拟保存到本地存储
          uni.setStorageSync(KEY_DRAFT, draftData);

          this.$refs.uToast.show({
            message: '草稿保存成功',
            type: 'success'
          });

        } catch (error) {
          console.error('保存草稿失败:', error);
          this.$refs.uToast.show({
            message: '保存失败，请重试',
            type: 'error'
          });
        }
      },
      async uploadFile(files) {
        let list = []
        for (let file of files) {
          let response = await uni.$u.http.upload('/api/rentout/uploadFile', {
            filePath: file,
            name: 'file',
          })

          let { code, message, result } = response.data
          if (code != 200) {
            throw new Error(message)
          }
          list.push(AppDefine.host + '/' + result.url)
        }
        return list
      },
      // 提交表单
      async handleSave() {
        try {
          console.log(this.formData)

          // 表单验证
          const valid = await this.$refs.uForm.validate();
          if (!valid) return;
          let files = await this.uploadFile(this.uploadedImages)
          this.isSubmitting = true;

          // 构建提交数据
          const submitData = {
            ...this.formData,
            tagsJson: JSON.stringify(this.selectedTags),
            imageUrls: JSON.stringify(files),
            phoneNumbers: JSON.stringify(this.phoneNumbers)
          }

          console.log('发布数据:', submitData);
          uni.$u.http.post('/api/house/publish', submitData).then(response => {
            let { code, result, message } = response.data
            if (code != 200) {
              this.$refs.uToast.show({
                message: message,
                type: 'error'
              });
              return
            }
            uni.showModal({
              title: '发布成功',
              content: `你已成功发布：${submitData.name}`,
              success: (res) => {
                this.$u.route({ type: 'back' })
                if (res.cancel) {
                  return
                }
                // 清除草稿
                uni.removeStorageSync(KEY_DRAFT);
              }
            })

          })

        } catch (error) {
          console.error('发布失败:', error);
          this.$refs.uToast.show({
            message: '发布失败，请重试',
            type: 'error'
          });
        } finally {
          this.isSubmitting = false;
        }
      },

    }
  }
</script>

<style lang="scss" scoped>
  .container {
    min-height: 100vh;
    background: #f8fafc;
    display: flex;
    flex-direction: column;
  }


  .info-card {
    background: white;
    border-radius: 24rpx;
    margin: 0 10rpx 10rpx;
    padding: 32rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
    border: 1rpx solid #f1f5f9;
  }

  .welcome-card {
    margin-top: 24rpx;

    .welcome-header {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin-bottom: 16rpx;

      .welcome-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .welcome-desc {
      font-size: 26rpx;
      color: #64748b;
      line-height: 1.5;
    }
  }

  .section-title {
    display: flex;
    align-items: center;
    gap: 12rpx;
    font-size: 28rpx;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 32rpx;
  }

  .tags-section {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 16rpx;
    gap: 10upx;
  }

  .custom-tag-input {
    margin-bottom: 16rpx;
  }

  .upload-section {
    .upload-desc {
      font-size: 26rpx;
      color: #64748b;
      margin-bottom: 24rpx;
      display: block;
    }

    .upload-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 24rpx;

      .upload-item {
        position: relative;

        .delete-btn {
          position: absolute;
          top: -12rpx;
          right: -12rpx;
          width: 48rpx;
          height: 48rpx;
          background: #ef4444;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 4rpx 12rpx rgba(239, 68, 68, 0.3);
        }
      }

      .upload-placeholder {
        width: 200rpx;
        height: 200rpx;
        background: #f8fafc;
        border: 2rpx dashed #cbd5e1;
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 12rpx;

        .upload-text {
          font-size: 24rpx;
          color: #94a3b8;
        }
      }
    }
  }

  .bottom-action-bar {
    display: flex;
    flex-direction: row;
    background: white;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #f1f5f9;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
    z-index: 100;
  }
</style>